<?php
/**
 * Created by PhpStorm.
 * User: lyh
 * Date: 2016/10/18
 * Time: 16:15
 */

namespace Community\Controller;
use Community\Model\ClientBookModel;
use Think\Controller;
use User\Model\UserModel;

class BookController extends Controller {
    public function _initialize(){
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:GET');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }
    /**
     * 点击预约服务，加载服务内容价格
     * parameter：fakeid 标识护工A、小组B、诊所C
     * parameter: token 当前用户
     * return:'head'内容
     *       'serviceplace' 服务地址
     *       'skill' 技能
     *       'detail' 服务详情数组
     *       'prise' 价格
     */
    public function bookService(){
        $fakeid=I('fakeid');//如果是加载护工只传A即可
        $token=I('token');
        if($token==''){
            echo json_encode($result['code']='3');
            return;
        }
        //根据token获取用户id
        $user = new UserModel();
        $user_id = $user->getIdByToken($token);
        //根据userid获取当前用户的被服务认信息
        $be_server = M('be_servepeople')->where(['user_id'=>$user_id,'be_status'=>1])->field('id,name,often,self_live,city,detail_adress')->select();
        $flag=substr($fakeid,0,1);//判断是护工、小组、诊所
        $id=(int)substr($fakeid,4);//获取相应的id号,从第四个开始往后取
        $server_typys = [];//服务类型
        $info = [];
        switch($flag){
            case 'A':
//                $info=M('person_table')->where(array('id'=>$id))->find();//当前护工的详细信息
                //获取当前护工的服务类型
//                $server_type_ids = M('person_server_type')->where(['person_id'=>$id])->getField('server_type_id',true);
//                $server_typys = M('server_type')->field('id as server_type_id,name as server_type_name')->where(['id'=>['in',$server_type_ids]])->select();
                $server_typys = M('server_type')->field('id as server_type_id,name as server_type_name')->select();
                //只是单价，后面前端提交购买数量，修改订单总价sumPrise
                break;
            case 'B':
                $info=M('group_table')->where(array('id'=>$id))->find();
                break;
            case 'C':
                $info=M('clinic_table')->where(array('id'=>$id))->find();
        }
        //组建被服务人的资料
        foreach ($be_server as $item){
            $info['be_server'][] = [
                'be_server_people_adress'=>$item['city'].$item['detail_adress'],//地址
                'be_server_people_name'=>$item['name'],//姓名
                'be_server_people_self_live'=>$item['self_live'],//是否自理
                'be_server_people_often'=>$item['often'],//是否常用
                'be_server_people_id'=>$item['id'],//id
            ];
        }
        //组件服务类型
        foreach ($server_typys as $item){
            //如果服务类型id为1即医院护理时
            //给标识flag为1，用于显示是否同意一对多
            if($item['server_type_id'] == 1){
                $server_type_flag = '1';
            }else{
                $server_type_flag = '0';
            }
            $info['server_type'][] = [
                'server_type_id'=>$item['server_type_id'],//服务类型id
                'server_type_name'=>$item['server_type_name'],//服务类型名称
                'server_type_flag'=>$server_type_flag,//服务类型标识
            ];
        }
        echo json_encode($info,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取服务类型对应的套餐
     * 参数：server_type_id ：服务类型id
     */
    public function getPackage(){
        //获取当前服务类型
        $server_type_id = I('post.server_type_id');
        //获取套餐
        $packages = M('package')->where(['server_type_id'=>$server_type_id])->select();
        foreach($packages as &$item){
            //如果套餐为1即全天护理时
            //返回标识，用于是否允许改变一对多按钮状态
            if($item['id'] == 1){
                $item['package_flag'] = '1';
            }else{
                $item['package_flag'] = '0';
            }
        }
        $this->ajaxReturn($packages);
    }

    /**
     * 添加被服务人
     */
    public function addBeServePeople(){
        $token=I('token');
        if($token==''){
            echo json_encode($result['code']='3');
            return;
        }
        //名字不能为空
        if(empty(I('post.name'))){
            $this->ajaxReturn(['status'=>0]);
            exit;
        }
        //根据token获取用户id
        $user = new UserModel();
        $user_id = $user->getIdByToken($token);
        $date = [
            'name'=>I('post.name'),
            'sex'=>I('post.sex'),
            'age'=>I('post.age'),
            'height'=>I('post.height'),
            'weight'=>I('post.weight'),
            'city'=>I('post.city'),
            'detail_adress'=>I('post.detail_adress'),
            'self_live'=>I('post.self_live'),
            'often'=>I('post.often'),
            'user_id'=>$user_id,
            'are_id_head'=>I('post.are_id_head'),
            'be_create_time'=>time(),
        ];
        //将其它的常用设为0
        if($date['often'] == 1){
            M('be_servepeople')->where(['user_id'=>$user_id])->save(['often'=>0]);
        }
        if(($id = M('be_servepeople')->add($date)) === false){
            $this->ajaxReturn(['status'=>0]);
            exit;
        }
        $this->ajaxReturn(['status'=>1]);
    }
    //删除被护理人
    public function removeBeServePeople() {
        $id = I('post.id');
        $token = I('post.token');
        //根据token获取user_id
        $user_model = new UserModel();
        $user_id = $user_model->getIdByToken($token);
        if(!$user_id){
            $this->ajaxReturn(['status'=>0,'msg'=>'请登录']);
        }
        $model = M('be_servepeople');
        //先判断是否为常用联系人
        if($model->where(['id'=>$id])->getField('often') == 1){
            //是的话将换一个常用联系人
            $often_id = $model->where(['user_id'=>$user_id,'id'=>['neq',$id],'be_status'=>1])->find();
            if($often_id){
                $model->where(['id'=>$often_id['id']])->setField(['often'=>1]);
            }
        }
        //为逻辑删除
        if($model->where(['id'=>$id,'user_id'=>$user_id])->setField(['be_status'=>0])){
            $this->ajaxReturn(['status'=>1,'msg'=>'删除成功']);
        }else{
            $this->ajaxReturn(['status'=>0,'msg'=>'删除失败']);
        }
    }
    //设置默认被护理人
    public function setDefaultBeServePeople() {
        $id = I('post.id');
        $token = I('post.token');
        //根据token获取user_id
        $user_model = new UserModel();
        $user_id = $user_model->getIdByToken($token);
        if(!$user_id){
            $this->ajaxReturn(['status'=>0,'msg'=>'请登录']);
        }
        $model = M('be_servepeople');
        //设置默认  先把其它的设置为0
        $res = $model->where(['user_id'=>$user_id,'be_status'=>1])->setField(['often'=>0]);
        if($res){
            if($model->where(['user_id'=>$user_id,'id'=>$id])->setField(['often'=>1])){
                $this->ajaxReturn(['status'=>1,'msg'=>'设置成功']);
            }else{
                $this->ajaxReturn(['status'=>0,'msg'=>'设置失败']);
            }
        }else{
            $this->ajaxReturn(['status'=>0,'msg'=>'设置失败']);
        }
    }

    /**
     * 点击预约，下订单操作
     * parameter: fakeid ,token,sumprise.....
     * return:
     *      'code':
     *      'message':
     *
     * 将后面已交易完成的订单，保存到hd_finish_book表中
     */
    public function placeAnOrder(){
        if(!IS_AJAX) E('网页不存在');
        $fakeid=I('fakeid');//获取标识 如果是加载护工只传A即可
        $token=I('token');//客户token
        if($token==''){
            echo json_encode($result['code']='3');
            return;
        }
        //根据token获取用户id
        $user = new UserModel();
        $user_id = $user->getIdByToken($token);
        $flag=substr($fakeid,0,1);//判断是护工、小组、诊所
        $id= (int)substr($fakeid,4);//获取相应的id号
        $beserve_id=I('beserve_id');//被服务人id
        $linkMan=I('linkman');//联系人
        $linkPhone=I('linkphone');//联系人电话
        $server_type_name = I('server_type_name');//服务类型名称
        $package_id = I('package_id');//套餐id
        $amount = I('amount');
        //判断套餐类型
        $package_info = M('package')->where(['id'=>$package_id])->find();
        if($package_info['unit'] == '天' && $amount <= 1){
            $this->ajaxReturn(['status'=>0,'msg'=>'该套餐至少选择两天']);exit;
        }
        //取价格
        switch($flag){
            case 'A':
//                $prise=M('person_table')->where(array('id'=>$id))->field('prise')->select();//只是单价，后面前端提交购买数量，修改订单总价sumPrise
//                $price=$prise[0]['prise'];
                //获取所有空闲护工的id
//                $person_ids  = M('PersonTable')->where(['status'=>1])->getField('id',true);
//                $person_id = $person_ids[array_rand($person_ids)];//随机抽取一个
                //根据套餐id 获取价格
                $price = M('package')->where(['id'=>$package_id])->getField('price');
                break;
            case 'B':
                $prise=M('group_table')->where(array('id'=>$id))->field('prise')->select();
                $price=$prise[0]['prise'];
                break;
            case 'C':
                $prise=M('clinic_table')->where(array('id'=>$id))->field('prise')->select();
                $price=$prise[0]['prise'];
                break;
        }
        $instruction=I('instruction');//备注
        $no = str_pad(rand(1,1000) , 4, "0", STR_PAD_LEFT);
        $ordid = date('YmdHis',time()) . $flag . $no;//生成订单号
        //构建订单
        $bookInfo=array(
            'starttime'=>time(),//下单时间
            'price'=>$price,//单价
            'amount'=>$amount,//数量，天数
            'user_id'=>$user_id,
            'fake_id'=>$id ? $fakeid : 'A',//id不存在说明为护工订单 fake_id为A
            'beserve_id'=>$beserve_id,//被服务人id
            'yesorno_eat'=>I('yesorno_eat'),//是否提供食宿
            'server_type'=>$server_type_name,//服务类型名称
            'package_id'=>$package_id,//套餐id
            'linkman'=>$linkMan,
            'linkphone'=>$linkPhone,
            'ordid'=>$ordid,
            'instruction'=>$instruction,//备注
            'servertime'=>I('servertime'),//服务时间
        );
        //服务时间不能在当前时间之前
        if($bookInfo['servertime'] < time()){
            echo json_encode(['status'=>'0']);exit;
        }
        $bid=M('client_book')->add($bookInfo);
        //判断是否添加订单成功
        if($bid) {
//            //添加成功调用alipay支付接口
//            $pay=new \Community\Controller\AlipayController();
//            $pay->alipay($ordid,$linkMan,$sumPrise*I('amount'),'无');
            echo json_encode(['status'=>'1','ordid'=>$ordid]);
        }else{
            //返回-1
            echo json_encode(['status'=>'0']);
        }
    }

    /**
     * 调用支付
     * @param $ordid    //订单id
     * @param $pay_type //支付方式
     */
    public function doPay($ordid,$pay_type){
        if(!IS_AJAX) E('网页不存在');
        $order_info = M('client_book')->where(['ordid'=>$ordid])->field('price,amount,linkman')->find();
        $sumPrise = $order_info['price'] * $order_info['amount'];
        //判断支付接口
        switch($pay_type){
            case 1:
                //支付宝接口
                $pay=new \Community\Controller\AlipayController();
                $pay->alipay($ordid,$order_info['linkman'],$sumPrise,'无');
                break;
            case 2:
                $pay = new WeixinController();
                $pay->test($ordid,$sumPrise,'无');
                break;
            case 3:
                break;
            case 4:
                break;
        }
    }

    /**
     * 商家，或者客户查看我的订单
     * Parameter：token,
     * Return:
     *      "name":
     *      "bookid":
     *      "time":Y-m-d
     *      "headurl":
     *      "status":完成状态
     */
    public function checkMyOrder(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $personCheck=M('person_table')->where(array('userid'=>$userid))->field('id')->select();
        $groupCheck=M('group_table')->where(array('userid'=>$userid))->field('id')->select();
        $clinicCheck=M('clinic_table')->where(array('userid'=>$userid))->field('id')->select();
        $info=array();
        if($personCheck)
        {
            $personCheckId='A888'.$personCheck[0]['id'];
        }
        if($groupCheck)
        {
            $groupCheckId='B888'.$groupCheck[0]['id'];
        }
        if($clinicCheck)
        {
            $clinicCheckId='C888'.$clinicCheck[0]['id'];
        }
        //查看是否设有护工商店
        if($personCheckId!='')
        {
            $data=M('client_book')->where(array('pid'=>$personCheckId))->field('bid,starttime,status,userid')->select();
            $userInfo=M('userdetail')->where(array('token'=>$token))->field('headurl,username')->select();
            for($i=0;$i<count($data);$i++)
            {
                $value=array(
                    'name'=>$userInfo[0]['username'],
                    'bookid'=>$data[$i]['bid'],
                    'time'=>$data[$i]['starttime'],
                    'headurl'=>$userInfo[0]['headurl'],
                    'ordstatus'=>$data[$i]['status']
                );
                    array_push($info,$value);
            }
        }

        //查看是否设有小组商店
        if($groupCheckId!='')
        {
            $data=M('client_book')->where(array('pid'=>$groupCheckId))->field('bid,starttime,status,userid')->select();
            $userInfo=M('userdetail')->where(array('token'=>$token))->field('headurl,username')->select();
            for($i=0;$i<count($data);$i++)
            {
                $value=array(
                    'name'=>$userInfo[0]['username'],
                    'bookid'=>$data[$i]['bid'],
                    'time'=>$data[$i]['starttime'],
                    'headurl'=>$userInfo[0]['headurl'],
                    'ordstatus'=>$data[$i]['status']
                );
                array_push($info,$value);
            }
        }

        //查看是否设有诊所商店
        if($clinicCheckId!='')
        {
            $data=M('client_book')->where(array('pid'=>$clinicCheckId))->field('bid,starttime,status,userid')->select();
            $userInfo=M('userdetail')->where(array('token'=>$token))->field('headurl,username')->select();
            for($i=0;$i<count($data);$i++)
            {
                $value=array(
                    'name'=>$userInfo[0]['username'],
                    'bookid'=>$data[$i]['bid'],
                    'time'=>$data[$i]['starttime'],
                    'headurl'=>$userInfo[0]['headurl'],
                    'ordstatus'=>$data[$i]['status']
                );
                array_push($info,$value);
            }
        }
        //客户查看我的订单
        if($personCheckId=='' && $groupCheckId=='' && $clinicCheckId=='')
        {
            $bookInfo=M('client_book')->where(array('userid'=>$userid))->select();
            for($i=0;$i<count($bookInfo);$i++)
            {
                $fakeid=$bookInfo[$i]['pid'];
                $flag=substr($fakeid,0,1);//判断是护工、小组、诊所
                $id=(int)substr($fakeid,4);//获取相应的id号
                switch($flag){
                    case 'A':
                        $masterInfo=M('person_table')->where(array('id'=>$id))->select();
                        break;
                    case 'B':
                        $masterInfo=M('group_table')->where(array('id'=>$id))->select();
                        break;
                    case 'C':
                        $masterInfo=M('clinic_table')->where(array('id'=>$id))->select();
                        break;
                }
                $value=array(
                    'name'=>$masterInfo[0]['username'],
                    'bookid'=>$bookInfo[$i]['id'],
                    'time'=>$bookInfo[$i]['starttime'],
                    'headurl'=>$masterInfo[0]['headurl'],
                    'ordstatus'=>$bookInfo[$i]['status']
                );
                array($info,$value);
            }
        }
        echo json_encode($info,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 用户查看订单列表
     * parameter:token 用户token
     *           status 状态码 0已关闭 1未付款 2进行中 3已完成
     * return:
     */
    public function showOrderList(){
        if(!IS_AJAX) E('网页不存在');
        $token = I('post.token');
        $status = I('post.status');//状态 0已关闭 1未付款 2进行中 3已完成
        $p=I('page',1,'intval');//分页
        //获取用户id
        $user = new UserModel();
        $user_id = $user->getIdByToken($token);
        //查询出当前用户当前状态的所有订单 包括被服务人信息
        $order_model = new ClientBookModel();
        $orders = $order_model->getOrderList($user_id,$status,$p);
        //实例化对象
        $person_model = M('person_table');
        $group_model = M('group_table');
        $clinic_model = M('clinic_table');
        //把订单对应的服务人信息添加到返回数据中
        foreach ($orders as &$order){
            $flag = substr($order['fake_id'],0,1);//A护工 B小组　C诊所
            $thisId = (int)substr($order['fake_id'],4);//对应的id
            //服务结束时间
            $order['serverendtime'] = $order['servertime'] + $order['amount'] * 24 * 3600;
            switch ($flag){
                case 'A':
//                    $row = $person_model->field('name,headurl')->where(['id'=>$thisId])->find();
                    $row = [];
                    $order = array_merge($order,$row);
                    break;
                case 'B':
                    $row = $group_model->field('name,headurl')->where(['id'=>$thisId])->find();
                    $order = array_merge($order,$row);
                    break;
                case 'C':
                    $row = $clinic_model->field('name,headurl')->where(['id'=>$thisId])->find();
                    $order = array_merge($order,$row);
                    break;
            }
        }
        $this->ajaxReturn($orders);
    }
    
    /***
     * 订单详情显示
     * parameter：id 订单id
     * return:
        id          订单id
        ordid,		订单号
        price,		单价
        amount,		数量（天或小时）
        fake_id,	A护工B小组C诊所+888+对应id
        linkman,	联系人姓名
        linkphone,	联系人电话
        servertype,	服务类型（1医院陪护 2居家陪护）
        servertime,	服务时间
        starttime,	下订单时间
        instruction，备注
        ordstatus,  状态码

        name,		被服务人姓名
        city,		城市
        detail_adress,	详细地址
        age,		年龄
        sex,		性别
        height,		身高
        weight,		体重
        self_live,	是否自理（'1不能自理','2半自理','3自理'）
        yesorno_eat,是否包吃住（0否1是）

        person_id,	服务人id
        person_name,服务人姓名
        headurl,	服务人头像
        wechat,		微信
        person_phone电话
     */
    public function showOrderDetail(){
//        if(!IS_AJAX) E('网页不存在');
        $id = I('id');
        //查询出订单详情 包括订单对应的被服务人的信息
        $order_model = new ClientBookModel();
        $info = $order_model->getOrderDetail($id);
        $fakeid = $info['fake_id'] ? $info['fake_id'] : 'A';
        $flag = substr($fakeid,0,1);//判断是护工、小组、诊所
        $id = (int)substr($fakeid,4);//获取相应的id号
        //获取对应的服务人的信息
        switch($flag){
            case 'A':
//                $server = M('person_table')->field('id as person_id,name as person_name,headurl,wechat,phone as person_phone')->where(array('id'=>$id))->find();
                    $server = [];
                break;
            case 'B':
                $server = M('group_table')->field('id as person_id,name as person_name,headurl,wechat,phone as person_phone')->where(array('id'=>$id))->find();
                break;
            case 'C':
                $server = M('clinic_table')->field('id as person_id,name as person_name,headurl,wechat,phone as person_phone')->where(array('id'=>$id))->find();
                break;
        }
        $result = array_merge($info,$server);
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 删除一个订单
     * parameter: id 订单id
     * return: status 0失败 1成功
     */
    public function deleteOrder(){
        if(!IS_AJAX) E('网页不存在');
        $id = I('post.id');
        $order_model = new ClientBookModel();
        if($order_model->removeOrder($id)){
            $this->ajaxReturn(['status'=>1]);
        }else{
            $this->ajaxReturn(['status'=>0]);
        }
    }

    /**
     * 评价
     */
    public function evaluateOrder(){
        if(!IS_AJAX) E('网页不存在');
        $id = I('post.id');//订单id
        $evaluate = I('post.evaluate');//评价分级1不满意 2满意
        $content = I('post.content');//评价内容
        $tag = I('post.tag');//评价标签
        if($evaluate != '1' && $evaluate != '2'){
            $evaluate = '2';
        }
        //获取订单信息
        $order_model = M('ClientBook');
        $order_info = $order_model->where(['id'=>$id])->find();
        //将订单状态改为已完成
        $order_model->where(['id'=>$id])->setField(['ordstatus'=>'3']);
        //将评价数据存入评价表
        $data = [
            'flag'=>substr($order_info['fake_id'],0,1),
            'pid'=>substr($order_info['fake_id'],4),
            'tag'=>$tag,
            'content'=>$content,
            'evaluate'=>$evaluate,
            'ordid'=>$order_info['ordid'],
            'create_time'=>time(),
            'user_id'=>$order_info['user_id'],
        ];
        if(M('Evaluate')->add($data)){
            $result = ['status'=>1];
        }else{
            $result = ['status'=>0];
        }
        $this->ajaxReturn($result);
    }


    /**
     *将超过15分钟还未支付的订单自动取消
     * 需要在---php命令行---执行该方法
     */
    public function clearTimeoutOrder(){
        $order_model = M('ClientBook');
        //死循环执行
        while(true){
            $time = time();
//            //获取已付款（进行中）的订单
//            $order_amount = $order_model->where(['ordstatus'=>2])->field('id,amount,servertime')->select();
//            foreach ($order_amount as $item){
//                //已完成订单为：当前时间 大于了 开始服务时间+服务天数+7天自动完成
//                $endtime = $item['servertime'] + $item['amount'] * 24 * 3600 + 7 * 24 * 3600;
//                //将已完成得订单状态设置为3  评价默认好评
//                if($endtime < $time){
//                    $order_model->where(['id'=>$item['id']])->setField(['ordstatus'=>'3','evaluate'=>'2']);
//                }
//            }
            //获取超时的订单id
            $cond = [
                'ordstatus'=>1,
                'starttime'=>['lt',$time-1800],
            ];
            $order_no = $order_model->where($cond)->count('id');
            if($order_no){
                $order_model->where($cond)->setField('ordstatus',0);
                echo $order_no . '--Be affected--' . date('Y-m-d H:i:s',$time) . "\r\n";
            }else{
//                echo '0--Be affected--' . $time . "\r\n";
            }
            //延迟15秒执行
            sleep(15);
        }
    }


}